/**************************************************************************************** 
 Copyright © 2003-2012 hbasesoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.hbasesoft.hamibot.event;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hbasesoft.framework.common.utils.date.DateUtil;
import com.hbasesoft.framework.db.TransactionUtil;
import com.hbasesoft.framework.message.core.event.EventListener;
import com.hbasesoft.hamibot.dao.AppLogDao;
import com.hbasesoft.hamibot.entity.AppLogEntity;
import com.hbasesoft.hamibot.service.IpService4Local;

import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.annotation.Resource;

/**
 * <Description> <br>
 * 
 * @author 王伟<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2024年12月24日 <br>
 * @since V1.0<br>
 * @see com.hbasesoft.hamibot.event <br>
 */
@Transactional
@Component
public class AppLogEventListener implements EventListener<AppLogEntity> {

    /** */
    @Resource
    private AppLogDao appLogDao;

    /** */
    @Resource
    private IpService4Local ipService4Local;

    /**
     * Description: <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @return <br>
     */
    @Override
    public String[] events() {
        return new String[] {
            "log"
        };
    }

    /**
     * Description: <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @param event
     * @param data <br>
     */
    @Override
    public void onEmmit(final String event, final AppLogEntity data) {
        if (StringUtils.isNotEmpty(data.getIp())) {
            data.setAddress(ipService4Local.getIpInfo(data.getIp()));
        }

        if (StringUtils.isNotEmpty(data.getUserAgent())) {
            UserAgent userAgent = UserAgent.parseUserAgentString(data.getUserAgent());
            data.setBrowser(userAgent.getBrowser().getName());
            OperatingSystem os = userAgent.getOperatingSystem();
            data.setOs(os.getName());
        }

        data.setCreateTime(DateUtil.getCurrentDate());

        TransactionUtil.withSession((tm, ts) -> {
            appLogDao.save(data);
        });
    }

}
